-- 保存时自动格式化（通过 conform.nvim）
return {
  "stevearc/conform.nvim",
  -- event = { "BufWritePre", "BufWritePost", "InsertLeave", "BufReadPost" },
  event = { "BufReadPre", "BufNewFile" },
  enabled = true,
  config = function()
    local conform = require("conform")

    conform.setup({
      -- 定义格式化器
      formatters_by_ft = {
        lua = { "stylua" },
        html = { "biome-check", "prettier" },
        css = { "biome-check", "prettier" },
        javascript = { "biome-check", "prettier" },
        typescript = { "biome-check", "prettier" },
        javascriptreact = { "prettier" },
        typescriptreact = { "prettier" },
        svelte = { "prettier" },
        json = { "prettier" },
        yaml = { "prettier" },
        markdown = { "prettier" },
        go = { "gofmt", "goimports" },
        -- sh = { "shfmt" },
        rust = { "rustfmt" },
        -- c = { "clang-format" },
        -- cpp = { "clang-format" },
        -- python = { "isort", "black" },
        python = function(bufnr)
          if
            require("conform").get_formatter_info("ruff_format", bufnr).available
          then
            return { "ruff_format" }
          else
            return { "isort", "black" }
          end
        end,

        -- 使用 "*" 表示所有文件类型的默认格式化器
        -- ["*"] = { "codespell" }, -- 拼写检查, 会自动更改,个人不太习惯
      },
      -- formatters_by_ft = {
      --   javascript = { "biome-check" },
      --   typescript = { "biome-check" },
      --   javascriptreact = { "biome-check" },
      --   typescriptreact = { "biome-check" },
      --   css = { "biome-check" },
      --   html = { "biome-check" },
      --   svelte = { "prettier" },
      --   json = { "prettier" },
      --   yaml = { "prettier" },
      --   graphql = { "prettier" },
      --   liquid = { "prettier" },
      --   lua = { "stylua" },
      --   -- python = { "black" },
      --   markdown = { "prettier", "markdown-toc" },
      --   -- ["markdown.mdx"] = { "prettier", "markdownlint", "markdown-toc" },
      --
      --   -- 使用 "*" 表示所有文件类型的默认格式化器
      --   ["*"] = { "codespell" }, -- 拼写检查
      -- },
      -- 自定义格式化器配置
      formatters = {
        shfmt = {
          prepend_args = { "-i", "2" }, -- 缩进2个空格
        },
        prettierd = {
          condition = function(ctx)
            return vim.fs.find(
              { ".prettierrc", ".prettierrc.json" },
              { path = ctx.filename, upward = true }
            )[1]
          end,
        },
        ["markdown-toc"] = {
          condition = function(_, ctx)
            for _, line in
              ipairs(vim.api.nvim_buf_get_lines(ctx.buf, 0, -1, false))
            do
              if line:find("<!%-%- toc %-%->") then
                return true
              end
            end
          end,
        },
        ["markdownlint-cli2"] = {
          condition = function(_, ctx)
            local diag = vim.tbl_filter(function(d)
              return d.source == "markdownlint"
            end, vim.diagnostic.get(ctx.buf))
            return #diag > 0
          end,
        },
      },

      -- 保存时自动格式化 (默认已启用)
      format_on_save = {
        timeout_ms = 3000,
        lsp_fallback = true, -- 如果无格式化器，尝试使用 LSP
        async = false,
      },

      -- 异步格式化
      async = true,

      -- 安静模式 (不显示通知)
      quiet = true,

      -- 自定义通知处理器
      notify_on_error = true,
    })

    -- 格式化回调函数
    local function html_format_callback()
      -- for _, client in pairs(vim.lsp.get_clients()) do
      --   print(client.name)
      -- end
      local clients = vim.lsp.get_clients({ name = "html" })
      if #clients > 0 then
        print("LSP Format")
        vim.lsp.buf.format({
          async = true,
          filter = function(client)
            return client.name == "html"
          end,
        })
      else
        print("Conform Format")
        -- 回退到其他格式化器
        -- require("conform").format { async = true }
        conform.format({
          lsp_fallback = true,
          async = false,
          timeout_ms = 1000,
        })
      end
    end

    vim.keymap.set({ "n", "v" }, "<leader>fc", function()
      conform.format({
        lsp_fallback = true,
        async = false,
        timeout_ms = 1000,
      })
      -- html_format_callback()
    end, { desc = "Format file or range (in visual mode) - conform.nvim" })
  end,
}
